/*
 * HSM Proxy Project.
 * Copyright (C) 2013 FedICT.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License version
 * 3.0 as published by the Free Software Foundation.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, see 
 * http://www.gnu.org/licenses/.
 */

package be.fedict.hsm.admin.webapp;

import java.io.Serializable;
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.ejb.EJB;
import javax.enterprise.context.Conversation;
import javax.enterprise.context.ConversationScoped;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.primefaces.context.RequestContext;

import be.fedict.hsm.admin.webapp.security.RolesAllowed;
import be.fedict.hsm.entity.ApplicationEntity;
import be.fedict.hsm.entity.KeyStoreEntity;
import be.fedict.hsm.entity.KeyStoreType;
import be.fedict.hsm.model.admin.KeyStoreManagerBean;
import be.fedict.hsm.model.exception.ExistingKeyStoreException;
import be.fedict.hsm.model.exception.KeyStoreInUseException;
import be.fedict.hsm.model.security.AdministratorRoles;

@Named("hsmProxyKeyStore")
@ConversationScoped
@RolesAllowed(AdministratorRoles.ADMINISTRATOR)
public class KeyStoreController implements Serializable {

	private static final long serialVersionUID = 1L;

	private static final Log LOG = LogFactory.getLog(KeyStoreController.class);

	@EJB
	private KeyStoreManagerBean keyStoreManagerBean;

	private String name;

	private KeyStoreType type;

	private String path;

	private String password;

	private int slotListIndex;

	private KeyStoreEntity selectedKeyStore;

	private String selectedKeyStoreAlias;

	@Inject
	private Conversation conversation;

	public List<KeyStoreEntity> getList() {
		return this.keyStoreManagerBean.getKeyStoreList();
	}

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void add(ActionEvent actionEvent) {
		boolean result;
		try {
			result = this.keyStoreManagerBean.addKeyStore(this.name, this.type,
					this.path, this.password, this.slotListIndex);
		} catch (ExistingKeyStoreException e) {
			FacesContext facesContext = FacesContext.getCurrentInstance();
			facesContext.addMessage("addForm:name", new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "Existing key store name.",
					null));
			return;
		}
		RequestContext requestContext = RequestContext.getCurrentInstance();
		requestContext.addCallbackParam("keyStoreAdded", true);
		FacesContext facesContext = FacesContext.getCurrentInstance();
		if (result) {
			facesContext.addMessage(null, new FacesMessage(
					FacesMessage.SEVERITY_INFO, "Added key store " + this.name,
					null));
		} else {
			facesContext.addMessage(null, new FacesMessage(
					FacesMessage.SEVERITY_WARN, "Error loading the key store "
							+ this.name, null));
		}
		this.name = null;
		this.type = null;
		this.path = null;
		this.password = null;
		this.slotListIndex = 0;
	}

	public void save(ActionEvent actionEvent) {
		boolean result = this.keyStoreManagerBean
				.saveKeyStore(this.selectedKeyStore);
		RequestContext requestContext = RequestContext.getCurrentInstance();
		requestContext.addCallbackParam("keyStoreSaved", true);
		FacesContext facesContext = FacesContext.getCurrentInstance();
		if (result) {
			facesContext.addMessage(null, new FacesMessage(
					FacesMessage.SEVERITY_INFO, "Saved and reloaded key store "
							+ this.selectedKeyStore.getName(), null));
		} else {
			facesContext.addMessage(null, new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "Error reloading key store "
							+ this.selectedKeyStore.getName(), null));
		}
		this.selectedKeyStore = null;
		this.conversation.end();
	}

	public KeyStoreType[] getTypes() {
		return KeyStoreType.values();
	}

	public KeyStoreType getType() {
		return this.type;
	}

	public void setType(KeyStoreType type) {
		this.type = type;
	}

	public String getPath() {
		return this.path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String getPassword() {
		return this.password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public int getSlotListIndex() {
		return this.slotListIndex;
	}

	public void setSlotListIndex(int slotListIndex) {
		this.slotListIndex = slotListIndex;
	}

	public void selectKeyStore(ActionEvent actionEvent) {
		UIComponent component = actionEvent.getComponent();
		Map<String, Object> attributes = component.getAttributes();
		this.selectedKeyStore = (KeyStoreEntity) attributes
				.get("selectedKeyStore");
		if (this.conversation.isTransient()) {
			this.conversation.begin();
		}
	}

	public void selectKeyStoreAlias(ActionEvent actionEvent) {
		UIComponent component = actionEvent.getComponent();
		Map<String, Object> attributes = component.getAttributes();
		this.selectedKeyStoreAlias = (String) attributes
				.get("selectedKeyStoreAlias");
		LOG.debug("selected key store alias: " + this.selectedKeyStoreAlias);
	}

	public List<CertificateView> getCertificates() {
		if (null == this.selectedKeyStoreAlias) {
			return Collections.EMPTY_LIST;
		}
		List<X509Certificate> certificateChain = this.keyStoreManagerBean
				.getCertificateChain(this.selectedKeyStore.getId(),
						this.selectedKeyStoreAlias);
		LOG.debug("getCertificates: " + certificateChain.size());
		List<CertificateView> certificateChainView = new LinkedList<CertificateView>();
		for (X509Certificate certificate : certificateChain) {
			CertificateView certificateView = new CertificateView(certificate);
			certificateChainView.add(certificateView);
		}
		return certificateChainView;
	}

	public void removeSelectedKeyStore(ActionEvent actionEvent) {
		try {
			this.keyStoreManagerBean.removeKeyStore(this.selectedKeyStore);
		} catch (KeyStoreInUseException e) {
			FacesContext facesContext = FacesContext.getCurrentInstance();
			facesContext.addMessage(null, new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "Key store "
							+ this.selectedKeyStore.getName() + " in use.",
					null));
			return;
		}
		RequestContext requestContext = RequestContext.getCurrentInstance();
		requestContext.addCallbackParam("keyStoreRemoved", true);
		FacesContext facesContext = FacesContext.getCurrentInstance();
		facesContext.addMessage(null, new FacesMessage(
				FacesMessage.SEVERITY_INFO, "Removed key store "
						+ this.selectedKeyStore.getName(), null));
		this.selectedKeyStore = null;
		this.conversation.end();
	}

	public String viewKeyStore(KeyStoreEntity keyStore) {
		this.selectedKeyStore = keyStore;
		if (this.conversation.isTransient()) {
			this.conversation.begin();
		}
		return "/admin/key-store";
	}

	public KeyStoreEntity getSelectedKeyStore() {
		return this.selectedKeyStore;
	}

	public String back() {
		this.conversation.end();
		return "/admin/key-stores";
	}

	public List<String> getSelectedKeyStoreAliases() {
		return this.keyStoreManagerBean
				.getKeyStoreAliases(this.selectedKeyStore.getId());
	}

	public List<ApplicationEntity> getSelectedKeyStoreApplications() {
		return this.keyStoreManagerBean
				.getKeyStoreApplications(this.selectedKeyStore.getId());
	}
}
